package com.blockchain.front.servlets.financial;

import java.io.IOException;
import java.math.BigDecimal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blockchain.framework.config.ConfigureProvider;
import com.blockchain.framework.http.servlet.annotation.PagingServlet;
import com.blockchain.framework.resource.PromptLevel;
import com.blockchain.framework.resource.ResourceRegister;
import com.blockchain.framework.service.ServiceSession;
import com.blockchain.framework.service.exception.LogicalException;
import com.blockchain.framework.service.exception.ParameterException;
import com.blockchain.front.service.financial.FinancialManage;
import com.blockchain.util.StringHelper;
import com.blockchain.variables.defines.SystemVariable;
@PagingServlet(itemServlet = Charge.class)
public class Charge extends AbstractFinancialServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void processGet(HttpServletRequest request, HttpServletResponse response, ServiceSession serviceSession)
			throws Throwable {
		forwardView(request, response, getClass());
	}
	@Override
	protected void processPost(HttpServletRequest request,
			HttpServletResponse response, ServiceSession serviceSession)
			throws Throwable {
		FinancialManage manage=serviceSession.getService(FinancialManage.class);
		BigDecimal amount = new BigDecimal(request.getParameter("amount"));
		String type = request.getParameter("type");
		String PaymentType = request.getParameter("PaymentType");
		if(StringHelper.isEmpty(PaymentType)){
			PaymentType = "";
		}

		ConfigureProvider configureProvider = ResourceRegister.getResourceProvider(getServletContext()).getResource(ConfigureProvider.class);
		
		BigDecimal usdRate = new BigDecimal(configureProvider.get("SYSTEM.USD_CNY_RATE"));
		
		int orderNo = manage.addOrder(amount, type,null, usdRate);
		if (orderNo > 0) {
			String url=configureProvider.format(SystemVariable.PAY_INDEX) + "?o="
					+ orderNo+"&radio="+PaymentType;
			sendRedirect(request, response,url);
			return;
		} else {
			sendRedirect(request, response,getController().getViewURI(request,CnyCz.class));
			return;
		}
	}

	@Override
	protected void onThrowable(HttpServletRequest request,
			HttpServletResponse response, Throwable throwable)
			throws ServletException, IOException {
		if (throwable instanceof LogicalException
				|| throwable instanceof ParameterException) {
			getController().prompt(request, response, PromptLevel.INFO,
					throwable.getMessage());
			sendRedirect(request, response,getController().getViewURI(request,CnyCz.class));
		}
	}

}
